import axios from 'axios';

const BASE_URL = 'http://localhost:8082'; // 后端API地址

/**
 * 获取所有订单列表
 * @returns {Promise<AjaxResult>} 返回订单列表
 */
export const getAllOrders = async () => {
  try {
    const response = await axios.get(`${BASE_URL}/orders`);
    return response.data;
  } catch (error) {
    console.error('获取所有订单失败:', error);
    throw error;
  }
};

/**
 * 分页获取订单列表
 * @param {number} pageNum - 页码
 * @param {number} pageSize - 每页数量
 * @returns {Promise<AjaxResult>} 返回分页订单列表
 */
export const getOrdersByPage = async (pageNum = 1, pageSize = 10) => {
  try {
    const response = await axios.get(`${BASE_URL}/orders/page?pageNum=${pageNum}&pageSize=${pageSize}`);
    return response.data;
  } catch (error) {
    console.error('分页获取订单失败:', error);
    throw error;
  }
};

/**
 * 条件分页查询订单 - 员工管理界面使用
 * @param {number} pageNum - 页码
 * @param {number} pageSize - 每页数量
 * @param {Object} condition - 查询条件
 * @returns {Promise<AjaxResult>} 返回条件查询结果
 */
export const pageByCondition = async (pageNum = 1, pageSize = 10, condition = {}) => {
  try {
    console.log('发送请求参数:', {
      pageNum,
      pageSize,
      condition
    });
    
    // 转换参数名称，确保与后端一致
    const orderCondition = {
      orderId: condition.orderId,
      userId: condition.userId,
      roomId: condition.roomId,
      paymentStatus: condition.paymentStatus,
      startTime: condition.startTime,
      endTime: condition.endTime
    };
    
    // 移除undefined的属性
    Object.keys(orderCondition).forEach(key => 
      orderCondition[key] === undefined && delete orderCondition[key]
    );
    
    const response = await axios.post(
      `${BASE_URL}/orders/page/condition?pageNum=${pageNum}&pageSize=${pageSize}`,
      orderCondition
    );
    
    console.log('接收响应数据:', response.data);
    return response.data;
  } catch (error) {
    console.error('条件分页查询订单失败:', error);
    throw error;
  }
};

/**
 * 获取订单详情
 * @param {number} orderId - 订单ID
 * @returns {Promise<AjaxResult>} 返回订单详情
 */
export const getOrderById = async (orderId) => {
  try {
    const response = await axios.get(`${BASE_URL}/orders/${orderId}`);
    return response.data;
  } catch (error) {
    console.error('获取订单详情失败:', error);
    throw error;
  }
};

/**
 * 更新订单状态 - 员工管理界面使用
 * @param {number} orderId - 订单ID
 * @param {Object} orderData - 更新的订单数据
 * @returns {Promise<AjaxResult>} 返回更新结果
 */
export const updateOrderStatus = async (orderId, orderData) => {
  try {
    const response = await axios.put(`${BASE_URL}/orders/${orderId}`, orderData);
    return response.data;
  } catch (error) {
    console.error('更新订单状态失败:', error);
    throw error;
  }
};

/**
 * 标记订单完成 - 员工管理界面使用
 * @param {number} orderId - 订单ID
 * @param {Object} completeData - 完成订单的数据
 * @returns {Promise<AjaxResult>} 返回操作结果
 */
export const completeOrder = async (orderId, completeData) => {
  try {
    const response = await axios.put(`${BASE_URL}/orders/${orderId}`, {
      orderId: orderId,
      paymentStatus: 2, // 设置为已完成
      ...completeData
    });
    return response.data;
  } catch (error) {
    console.error('标记订单完成失败:', error);
    throw error;
  }
};


/**
 * 更新订单
 * @param {number} orderId - 订单ID
 * @param {Object} orderData - 更新的订单数据
 * @returns {Promise<AjaxResult>} 返回更新结果
 */
export const updateOrder = async (orderId, orderData) => {
  try {
    const response = await axios.put(`${BASE_URL}/orders/${orderId}`, orderData);
    return response.data;
  } catch (error) {
    throw error;
  }
};

/**
 * 取消订单
 * @param {number} orderId - 订单ID
 * @returns {Promise<AjaxResult>} 返回取消结果
 */
export const cancelOrder = async (orderId) => {
  try {
    const response = await axios.delete(`${BASE_URL}/orders/${orderId}`);
    return response.data;
  } catch (error) {
    throw error;
  }
};

/**
 * 生成预约订单
 * @param {Object} orderData - 订单数据
 * @param {string} orderData.userId - 用户ID
 * @param {string} orderData.roomId - 会议室ID
 * @param {string} orderData.startTime - 预约开始时间 (ISO 8601 格式)
 * @param {string} orderData.endTime - 预约结束时间 (ISO 8601 格式)
 * @returns {Promise<AjaxResult>} 返回订单创建结果
 */
export const createReservationOrder = async (orderData) => {
  try {
    const response = await axios.post(`${BASE_URL}/orders/reserve`, orderData);
    return response.data;
  } catch (error) {
    throw error;
  }
};

/**
 * 根据用户ID获取订单列表
 * @param {string} userId - 用户ID
 * @returns {Promise<AjaxResult>} 返回用户订单列表
 */
export const getOrdersByUserId = async (userId) => {
  try {
    const response = await axios.get(`${BASE_URL}/orders/user/${userId}`);
    return response.data;
  } catch (error) {
    throw error;
  }
};

/**
 * 模拟支付订单
 * @param {number} orderId - 订单ID
 * @returns {Promise<AjaxResult>} 返回支付结果
 */
export const payOrder = async (orderId) => {
  try {
    const response = await axios.post(`${BASE_URL}/orders/pay/${orderId}`);
    return response.data;
  } catch (error) {
    throw error;
  }
};

/**
 * 获取订单支付的剩余时间
 * @param {number} orderId - 订单ID
 * @returns {Promise<AjaxResult>} 返回剩余时间
 */
export const getTimeDifference = async (orderId) => {
  try {
    const response = await axios.get(`${BASE_URL}/orders/time-diff/${orderId}`);
    return response.data;
  } catch (error) {
    throw error;
  }
};



/**
 * 获取可退款的订单列表
 * @returns {Promise<AjaxResult>} 返回可退款订单列表
 */
export const getRefundableOrders = async () => {
  try {
    const response = await axios.get(`${BASE_URL}/orders/refund/orders`);
    return response.data;
  } catch (error) {
    console.error('获取可退款订单失败:', error);
    throw error;
  }
};

/**
 * 更新订单状态
 * @param {number} orderId - 订单ID
 * @param {number} newStatus - 新状态值 (0:已预约, 1:已支付, 2:已退款, 3:已失效, 4:待退款, 5:使用中, 6:已完成)
 * @returns {Promise<AjaxResult>} 返回更新结果
 */
export const setOrderStatus = async (orderId, newStatus) => {
  try {
    console.log(`尝试更新订单状态: orderId=${orderId}, newStatus=${newStatus}`);
    
    // 确保参数是数字类型
    const numOrderId = parseInt(orderId, 10);
    const numStatus = parseInt(newStatus, 10);
    
    // 使用标准的params方式传递参数
    const response = await axios.get(`${BASE_URL}/orders/update/status`, {
      params: {
        orderId: numOrderId,
        newStatus: numStatus
      }
    });
    
    console.log('更新订单状态响应:', response.data);
    return response.data;
  } catch (error) {
    console.error('更新订单状态失败:', error);
    console.error('错误详情:', error.response ? error.response.data : '无响应数据');
    throw error;
  }
};

/**
 * 取消订单并处理退款
 * @param {number} orderId - 订单ID
 * @returns {Promise<AjaxResult>} 返回退款结果
 */
export const updateOrderStatusWithRefund = async (orderId) => {
  try {
    const response = await axios.get(`${BASE_URL}/orders/update/status/refund?orderId=${orderId}`);
    return response.data;
  } catch (error) {
    console.error('取消订单并退款失败:', error);
    throw error;
  }

};

/**
 * 根据多个用户ID分页查询订单列表
 * @param {number} pageNum - 页码
 * @param {number} pageSize - 每页数量
 * @param {Array<number>} userIds - 用户ID列表
 * @param {number} paymentStatus - 支付状态
 * @returns {Promise<AjaxResult>} 返回分页订单列表
 */
export const getOrdersByUserIds = async (pageNum = 1, pageSize = 10, userIds = [], paymentStatus = undefined) => {
  try {
    const response = await axios.post(
      `${BASE_URL}/orders/page/by-userids?pageNum=${pageNum}&pageSize=${pageSize}`,
      { userIds, ...(paymentStatus !== undefined && { paymentStatus }) }
    );
    return response.data;
  } catch (error) {
    console.error('根据用户ID列表查询订单失败:', error);
    throw error;
  }
};
